package com.qiguliuxing.dts.db.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiguliuxing.dts.db.dao.DtsFootprintMapper;
import com.qiguliuxing.dts.db.domain.DtsFootprint;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DtsFootprintService {
    @Resource
    private DtsFootprintMapper footprintMapper;

    public List<DtsFootprint> queryByAddTime(Integer userId, Integer page, Integer size) {
        QueryWrapper<DtsFootprint> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DtsFootprint::getUserId, userId);
        queryWrapper.eq("deleted", false);
        queryWrapper.orderByDesc("add_time");
        IPage<DtsFootprint> iPage = new Page<>(page, size);
        return footprintMapper.selectPage(iPage, queryWrapper).getRecords();
    }

    public DtsFootprint findById(Integer id) {
        return footprintMapper.selectById(id);
    }

    public void deleteById(Integer id) {
        footprintMapper.deleteById(id);
    }

    public void add(DtsFootprint footprint) {
        footprint.setAddTime(LocalDateTime.now());
        footprint.setUpdateTime(LocalDateTime.now());
        footprintMapper.insert(footprint);
    }

    public List<DtsFootprint> querySelective(String userId, String goodsId, Integer page, Integer size, String sort,
                                             String order) {
        QueryWrapper<DtsFootprint> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(userId)) {
            queryWrapper.lambda().eq(DtsFootprint::getUserId, userId);
        }
        if (StrUtil.isNotEmpty(goodsId)) {
            queryWrapper.lambda().eq(DtsFootprint::getGoodsId, goodsId);
        }
        queryWrapper.eq("deleted", false);
        if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
            queryWrapper.orderByDesc(sort);
        }
        queryWrapper.orderByDesc("add_time");
        IPage<DtsFootprint> iPage = new Page<>(page, size);
        return footprintMapper.selectPage(iPage, queryWrapper).getRecords();
    }
}
